package com.groupbuying.easyexcel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MqListener implements MessageListener {

    public static final Logger LOGGER = LoggerFactory.getLogger(MqListener.class);

    @Autowired
    private QueryInfoDao queryInfoDao;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        if (message.getTopic().equals(Constant.MQ_TOPIC)) {
            /* 获取消息重试次数 */
            int reconsume = message.getReconsumeTimes();
            if (reconsume >= 3) {
                /* 消息已经重试了超过或等于3次，告诉服务器稍后再尝试消费 */
                return Action.ReconsumeLater;
            }

            if (StringUtils.isNotEmpty(message.getTag()) && message.getTag()
                    .equals(Constant.MQ_ACCESS_TAG)) {
                try {


                    /* 对应json包体结构如下 */
                    /* String jsonStr = "{\"sql\":\"select storeName,storeId, storeNo from ywxd_store_flow_by_day where storeId = '001558f8d2a2423f89c3ed46f8b42cbf' \",\"desc\":\"测试sql\",\"title\":[\"商店名称\",\"商店ID\",\"商店编号\"],\"titleAmount\":\"3\"}"; */
                    String jsonStr = new String(message.getBody());

                    /* 解析为jsonObject */
                    JSONObject jsonObject = JSON.parseObject(jsonStr);

                    /* 执行的sql */
                    String sql = jsonObject.getString("sql").trim();

                    /* 生成MD5值的SQL */
                    String compressSql = sql.replaceAll("\\s*", "");

                    /* 通过sql生成唯一MD5值 */
                    String id = DigestUtils.md5DigestAsHex(compressSql.getBytes());

                    /* Excel头部 */
                    List<String> listTitle = JSONObject.parseArray(jsonObject.getJSONArray("title").toJSONString(), String.class);

                    /* Excel头部个数 */
                    int titleAmount = jsonObject.getIntValue("titleAmount");

                    /* JSON传入Title个数校验 */
                    if(titleAmount != listTitle.size()){
                        return Action.CommitMessage;
                    }

                    /* id数据库判重 */
                    if(0 != queryInfoDao.count(id)){
                        return Action.CommitMessage;
                    };

                    /* 生成excel，并放入oss中 */
                    List<Map<String, Object>> mapList = queryInfoDao.executeSql(sql);
                    Map<String, String> returnMap = ExcelUtil.generateExcel(mapList, id, listTitle);

                    /* 记录生成记录 */
                    Map<String, String> map = new HashMap<>();
                    map.put("id", id);
                    map.put("sql", jsonObject.getString("sql"));
                    map.put("desc", jsonObject.getString("desc"));
                    map.put("correspondExcelName", returnMap.get("fileName"));
                    map.put("correspondOssAddress", returnMap.get("fileUrl"));
                    map.put("fileGenerationFlag", "1");

                    /* 存储到数据库 */
                    queryInfoDao.save(map);

                    System.out.println("Receive: " + message);
                    return Action.CommitMessage;

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        return Action.CommitMessage;
    }

}
